package com.taxshare.seller.service;
import com.google.common.collect.Lists;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taxshare.response.beans.Response;
import com.taxshare.seller.constant.CodeConstant;
import com.taxshare.seller.constant.PrinterConstant;
import com.taxshare.seller.entity.EquipmentEntity;
import com.taxshare.seller.entity.SellerInvoiceDetailEntity;
import com.taxshare.seller.entity.SellerInvoiceEntity;
import com.taxshare.seller.entity.SellerPrintConfigEntity;
import com.taxshare.seller.mapper.SellerUserPrintMapper;
import com.taxshare.seller.remote.ApiClientService;
import com.taxshare.seller.service.sst.IntJsonUtil;
import com.taxshare.seller.util.HttpUtils;
import com.taxshare.seller.util.SmartHttpUtil;
import com.taxshare.seller.view.dto.SellerInvoiceDTO;
import com.taxshare.seller.view.dto.SyncInvoiceDTO;
import com.taxshare.seller.view.dto.SynchronizeInvoiceDTO;
import com.taxshare.seller.view.vo.printer.*;
import com.taxshare.tools.util.DoubleUtils;
import com.taxshare.tools.util.StringUtil;
import com.taxshare.tools.util.UUIDUitl;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.apache.bcel.classfile.Code;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


@Service
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
@Slf4j
public class PrinterService extends ServiceImpl<SellerUserPrintMapper, SellerPrintConfigEntity> {

    @Autowired
    private InvoicedService invoiceService;

    @Autowired
    private InvoiceDetailService invoiceDetailService;

    @Autowired
    EquipmentService equipmentService;

    @Autowired
    ApiClientService apiClientService;

    /**
     * 检测是否安装或打开税神通服务
     * @return
     */
    public Response checkPrinter(){
        try {
            PrinterRespVO resp = JSON.parseObject(SmartHttpUtil.sendGet(PrinterConstant.PRINT_VERSION,null,null), PrinterRespVO.class);
            if(PrinterConstant.PRINTER0000.equals(resp.getRetcode())){
                return Response.success();
            }else {
                Response.error(resp.getRetcode(),resp.getMsg(),resp.getData());
            }
        }catch (Exception e){
            return Response.error();
        }
        return Response.success();
    }

    /**
     * 获取当前连接的打印机信息
     * @return
     */
    public Response printGetPrintList(){
        try {
            PrinterRespVO resp = JSON.parseObject(SmartHttpUtil.sendGet(PrinterConstant.PRINT_GET_PRINT_LIST,null,null), PrinterRespVO.class);
            if(PrinterConstant.PRINTER0000.equals(resp.getRetcode())){
                return Response.success(Arrays.asList(resp.getData()));
            }else {
                Response.error(resp.getRetcode(),resp.getMsg(),resp.getData());
            }
        }catch (Exception e){
            return Response.error();
        }
        return Response.success();
    }


    /**
     * 设置默认打印机
     * @return
     */
    public  Response printSetprint(String printName){
        try {
            Map map = new HashMap();
            map.put("printname", printName);
            PrinterRespVO resp = JSON.parseObject(SmartHttpUtil.sendPostForm(PrinterConstant.PRINT_SETPRINT,map,null), PrinterRespVO.class);
            if(PrinterConstant.PRINTER0000.equals(resp.getRetcode())){
                return Response.success();
            }else {
                return Response.error(resp.getRetcode(),resp.getMsg(),resp.getData());
            }
        }catch (Exception e){
            log.error("-1",e);
            return Response.error();
        }
    }

    /**
     * 初始化打印机地址
     * @return
     */
    public Response printInitprint(){
        try {
            Map map = new HashMap();
            map.put("url", PrinterConstant.PRINT_DEFAULT_AFFRESS);
            PrinterRespVO resp = JSON.parseObject(SmartHttpUtil.sendPostForm(PrinterConstant.PRINT_INITPRINT,map,null), PrinterRespVO.class);
            if(PrinterConstant.PRINTER0000.equals(resp.getRetcode())){
                return Response.success();
            }else {
                return Response.error(resp.getRetcode(),resp.getMsg(),resp.getData());
            }
        }catch (Exception e){
            log.error("-1",e);
            return Response.error();
        }
    }

    /**
     * 自定义打印清单
     * @return
     */
    public  Response printZdyQdfp(PrintReqVO vo){
        if(StrUtil.isBlank(vo.getSerialNo()) || StrUtil.isBlank(vo.getPrintName())){
            return Response.error("SEL_107");
        }
        Response respSet = printSetprint(vo.getPrintName());
        if(!CodeConstant.T0000.equals(respSet.getCode())){
            return Response.error("SEL_109");
        }
        Response respInit = printInitprint();
        if(!CodeConstant.T0000.equals(respInit.getCode())){
            return Response.error("SEL_110");
        }
//        try {
//            //保存用户配置信息
//            SellerPrintConfigEntity sellerUserPrintEntity = (SellerPrintConfigEntity) getSellerUserPrint().getData();
//            if (sellerUserPrintEntity == null) {
//                sellerUserPrintEntity = new SellerPrintConfigEntity(
//                        UUIDUitl.UUID32(false),
//                        UserInfoUtil.getUserID(),
//                        UserInfoUtil.getUserNickName(),
//                        vo.getLeft(),
//                        vo.getTop(),
//                        vo.getPrintName());
//                baseMapper.insert(sellerUserPrintEntity);
//            } else {
//                sellerUserPrintEntity = new SellerPrintConfigEntity(
//                        UserInfoUtil.getUserID(),
//                        UserInfoUtil.getUserNickName(),
//                        vo.getLeft(),
//                        vo.getTop(),
//                        vo.getPrintName());
//                baseMapper.updateById(sellerUserPrintEntity);
//            }
//        }catch (Exception e){
//            log.error("保存用户信息异常",e);
//        }
        SellerInvoiceEntity sellerInvoiceEntity = invoiceService.getOne(new QueryWrapper<SellerInvoiceEntity>().eq("serial_no", vo.getSerialNo()));
        List<SellerInvoiceDetailEntity> sellerInvoiceDetailEntityList = invoiceDetailService.list(new QueryWrapper<SellerInvoiceDetailEntity>().eq("serial_no", vo.getSerialNo()));
        if(sellerInvoiceEntity == null || sellerInvoiceDetailEntityList == null || sellerInvoiceDetailEntityList.size() == 0){
            return Response.error("SEL_107");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("fplxdm",  PrinterConstant.coverInvoiceType(sellerInvoiceEntity.getInvoiceType()));
        map.put("left", vo.getLeft());
        map.put("top", vo.getTop());
        map.put("sfyl", "1");
        map.put("qdbz", "0");
        map.put("fpxx",JSON.toJSONString(invoiceToPrinterVo(sellerInvoiceEntity,sellerInvoiceDetailEntityList), SerializerFeature.WriteNullStringAsEmpty));
        try {
            PrinterRespVO resp = JSON.parseObject(HttpUtils.sendPost(PrinterConstant.PRINT_ZDYQDFP,map), PrinterRespVO.class);
            if(PrinterConstant.PRINTER0000.equals(resp.getRetcode())){
                return Response.success();
            }else {
                return Response.error(resp.getRetcode(),resp.getMsg(),resp.getData());
            }
        }catch (Exception e){
            return Response.error();
        }
    }

    /**
     * 发票信息转换
     * @param sellerInvoiceEntity
     * @param sellerInvoiceDetailEntityList
     * @return
     */
    private PrinterServiceRespVO invoiceToPrinterVo(SellerInvoiceEntity sellerInvoiceEntity, List<SellerInvoiceDetailEntity> sellerInvoiceDetailEntityList){
        PrinterServiceRespVO vo = new PrinterServiceRespVO();
        vo.setFplxdm(PrinterConstant.coverInvoiceType(sellerInvoiceEntity.getInvoiceType()));
        vo.setNsrmc(sellerInvoiceEntity.getSellerName());
        vo.setNsrsbh(sellerInvoiceEntity.getSellerTaxNo());
        vo.setSbbh("0");
        vo.setData(sellerInvoiceToPrinterVo(null,sellerInvoiceEntity,sellerInvoiceDetailEntityList));
        return vo;
    }

    /**
     * 发票信息转vo
     * @param sellerInvoiceEntity
     * @param sellerInvoiceDetailEntityList
     * @return
     */
    private List<PrinterInvoiceVO> sellerInvoiceToPrinterVo(List<SellerInvoiceEntity> sellerInvoiceEntityList,SellerInvoiceEntity sellerInvoiceEntity ,List<SellerInvoiceDetailEntity> sellerInvoiceDetailEntityList){
      List<PrinterInvoiceVO>  voList = new ArrayList<>();
      List<PrintcarInvoiceVO> vos = new ArrayList<>();
       if(sellerInvoiceEntityList == null && sellerInvoiceDetailEntityList != null){
           voList.add(sellerInvoiceToPrinter(sellerInvoiceEntity,sellerInvoiceDetailEntityList));
       }else {
           for (SellerInvoiceEntity sellerInvoice : sellerInvoiceEntityList) {
               QueryWrapper<SellerInvoiceDetailEntity> detailQueryWrapper = new QueryWrapper<>();
               detailQueryWrapper.eq("serial_no", sellerInvoice.getSerialNo());
               detailQueryWrapper.orderByAsc("invoice_sort");
               List<SellerInvoiceDetailEntity> detailEntityList = invoiceDetailService.list(detailQueryWrapper);
               if (detailEntityList == null || detailEntityList.size() == 0) {
                   return null;
               }
               if (CodeConstant.INVOICETYPE_JDC.equals(sellerInvoiceEntity.getInvoiceType())){
                   voList.add(sellerInvoiceToPrinter(sellerInvoice,detailEntityList));
               }else {
                   vos.add(sellerCarInvoiceToPrinter(sellerInvoice,detailEntityList));
               }
           }
       }
        return voList;
    }

    /**
     * 发票信息转vo
     * @param sellerInvoiceEntity
     * @param sellerInvoiceDetailEntityList
     * @return
     */
    private PrinterInvoiceVO sellerInvoiceToPrinter(SellerInvoiceEntity sellerInvoiceEntity ,List<SellerInvoiceDetailEntity> sellerInvoiceDetailEntityList){
        PrinterInvoiceVO vo = new PrinterInvoiceVO();
        if (CollUtil.isNotEmpty(sellerInvoiceDetailEntityList)) {
            int detailSize = sellerInvoiceDetailEntityList.size();
            if (detailSize >= 8) {
                vo.setQdbz(CodeConstant.COMM_CODE_1);
            } else {
                vo.setQdbz(CodeConstant.COMM_CODE_0);
            }
        } else {
            vo.setQdbz(CodeConstant.COMM_CODE_0);
        }
        vo.setKplx(sellerInvoiceEntity.getMakeInvoiceType());
        vo.setHjje(DoubleUtils.doubleFormatDec(sellerInvoiceEntity.getTotalSum()));
        vo.setGhdwdzdh(sellerInvoiceEntity.getPurchaserAddressTel());
        vo.setYfphm(sellerInvoiceEntity.getOldInvoiceNo());
        vo.setYfpdm(sellerInvoiceEntity.getOldInvoiceCode());
        if(StrUtil.isNotBlank(sellerInvoiceEntity.getInvoiceDate())){
            vo.setKprq(sellerInvoiceEntity.getInvoiceDate().replaceAll("-",""));
        }
        vo.setGhdwsbh(sellerInvoiceEntity.getPurchaserTaxNo());
        vo.setBz(sellerInvoiceEntity.getRemark());
        vo.setSkr(sellerInvoiceEntity.getPayee());
        vo.setGhdwmc(sellerInvoiceEntity.getPurchaserName());
        vo.setFpdm(sellerInvoiceEntity.getInvoiceCode());
        vo.setFphm(sellerInvoiceEntity.getInvoiceNo());
        vo.setHjse(DoubleUtils.doubleFormatDec(sellerInvoiceEntity.getTotalTax()));
        vo.setXhdwdzdh(sellerInvoiceEntity.getSellerAddressTel());
        vo.setMw(sellerInvoiceEntity.getCipherText());
        vo.setKpr(sellerInvoiceEntity.getDrawer());
        vo.setFhr(sellerInvoiceEntity.getReviewer());
        vo.setFplxdm(PrinterConstant.coverInvoiceType(sellerInvoiceEntity.getInvoiceType()));
        String invoiceState = sellerInvoiceEntity.getInvoiceState();
        String makeInvoiceType = sellerInvoiceEntity.getMakeInvoiceType();
        if (CodeConstant.COMM_CODE_0.equals(invoiceState) &&CodeConstant.COMM_CODE_1.equals(makeInvoiceType)) {
            vo.setFpzt(CodeConstant.COMM_CODE_1);
        }else {
            vo.setFpzt(PrinterConstant.coverInvoiceState(sellerInvoiceEntity.getInvoiceState()));
        }
        vo.setGhdwyhzh(sellerInvoiceEntity.getPurchaserBankAccount());
        vo.setJshj(DoubleUtils.doubleFormatDec(sellerInvoiceEntity.getTotalSumTax()));
        vo.setXhdwyhzh(sellerInvoiceEntity.getSellerBankAccount());
        vo.setJym(sellerInvoiceEntity.getCheckCode());
        List<PrinterInvoiceDetilVO> mxVo = sellerInvoiceToPrinterDetilVO(sellerInvoiceDetailEntityList);
        vo.setMx(mxVo);
        if(mxVo.size() == 1 && "2".equals(mxVo.get(0).getSlbs())){
            vo.setHjse("0.00");
        }
        return vo;
    }

    /**
     * 发票明细信息转vo
     * @param list
     * @return
     */
    private List<PrinterInvoiceDetilVO> sellerInvoiceToPrinterDetilVO(List<SellerInvoiceDetailEntity> list){
        List<PrinterInvoiceDetilVO> voList = new ArrayList<>();
        for(SellerInvoiceDetailEntity entity:list){
            PrinterInvoiceDetilVO vo = new PrinterInvoiceDetilVO();
            vo.setGgxh(entity.getModel());
            vo.setSpsl(entity.getGoodsNumber());
            vo.setYhzcbs(entity.getPreferentialMark());
            vo.setZzstsgl(entity.getPreferentialName());
            if(entity.getGoodsName().contains("*")){
                vo.setSpmc(entity.getGoodsName());
            }else{
                vo.setSpmc(getTaxName(entity.getTaxCode())+entity.getGoodsName());
            }
            vo.setDj(entity.getUnitPrice());
            vo.setXh(entity.getDetailNo());
            //vo.setZxbm(entity);
            vo.setFphxz(entity.getInvoiceRowNature());
            if("2".equals(entity.getTaxRateMark())){
                vo.setSe("0.00");
                vo.setSl("0.00");
            }else {
                vo.setSe(DoubleUtils.doubleFormatDec(entity.getGoodTax()));
                vo.setSl(DoubleUtils.doubleFormatDec(entity.getTaxRate()));
            }
            vo.setHsbz(entity.getTaxSign());
            vo.setDw(entity.getUnit());
            vo.setJe(DoubleUtils.doubleFormatDec(entity.getGoodsSum()));
            vo.setSpbm(entity.getTaxCode());
            vo.setSlbs(entity.getTaxRateMark());
            voList.add(vo);
        }
        return voList;
    }


    /**
     * 发票信息转vo
     * @param sellerInvoiceEntity
     * @param sellerInvoiceDetailEntityList
     * @return
     */
    private PrintcarInvoiceVO sellerCarInvoiceToPrinter(SellerInvoiceEntity sellerInvoiceEntity ,List<SellerInvoiceDetailEntity> sellerInvoiceDetailEntityList){
        PrintcarInvoiceVO vo = new PrintcarInvoiceVO();
        vo.setKplx(sellerInvoiceEntity.getMakeInvoiceType());
        vo.setHjje(DoubleUtils.doubleFormatDec(sellerInvoiceEntity.getTotalSum()));
        vo.setGhdwdzdh("");
        vo.setKpjh(sellerInvoiceDetailEntityList.get(0).getMachinNo());
        vo.setYfphm(sellerInvoiceEntity.getOldInvoiceNo());
        vo.setZfrq("");
        vo.setYfpdm(sellerInvoiceEntity.getOldInvoiceCode());
        String invoiceState = sellerInvoiceEntity.getInvoiceState();
        String makeInvoiceType = sellerInvoiceEntity.getMakeInvoiceType();
        if (CodeConstant.COMM_CODE_0.equals(invoiceState) &&CodeConstant.COMM_CODE_1.equals(makeInvoiceType)) {
            vo.setFpzt(CodeConstant.COMM_CODE_1);
        }else {
            vo.setFpzt(PrinterConstant.coverInvoiceState(sellerInvoiceEntity.getInvoiceState()));
        }
        vo.setFpdm(sellerInvoiceEntity.getInvoiceCode());
        vo.setFphm(sellerInvoiceEntity.getInvoiceNo());
        vo.setSfzhm(sellerInvoiceDetailEntityList.get(0).getIdCardNo());
        vo.setScqymc(sellerInvoiceDetailEntityList.get(0).getProductionCompanyName());
        vo.setCllx(sellerInvoiceDetailEntityList.get(0).getCarCategoryName());
        vo.setCpxh(sellerInvoiceDetailEntityList.get(0).getBrandMode());
        vo.setCd(sellerInvoiceDetailEntityList.get(0).getProductionPlaceName());
        vo.setHgzh(sellerInvoiceDetailEntityList.get(0).getCertificateNum());
        vo.setJkzmsh(sellerInvoiceDetailEntityList.get(0).getImportTestimonialNum());
        vo.setSjdh(sellerInvoiceDetailEntityList.get(0).getInspectionOdd());
        vo.setFdjhm(sellerInvoiceDetailEntityList.get(0).getEngineNum());
        vo.setCjhm(sellerInvoiceDetailEntityList.get(0).getCarDiscernCode());
        vo.setJshj(sellerInvoiceEntity.getTotalSumTax());
        vo.setDh(sellerInvoiceEntity.getSellerPhone());
        vo.setZh(sellerInvoiceEntity.getSellerBankAccount());
        vo.setDz(sellerInvoiceEntity.getSellerAddress());
        vo.setKhyh(sellerInvoiceEntity.getSellerDepositBank());
        vo.setZzssl(sellerInvoiceEntity.getTaxRate());
        vo.setZfr("");
        vo.setZzsse(sellerInvoiceEntity.getTotalTax());
        vo.setLslbs("0");
        vo.setSwjgdm(sellerInvoiceDetailEntityList.get(0).getTaxOfCode());
        vo.setSwjgmc(sellerInvoiceDetailEntityList.get(0).getTaxOfName());
        vo.setBhsj(sellerInvoiceEntity.getTotalSum());
        vo.setGhfsbh(sellerInvoiceEntity.getPurchaserCode());
        vo.setGhfmc(sellerInvoiceEntity.getPurchaserName());
        vo.setMw(sellerInvoiceEntity.getCipherText());
        if(StrUtil.isNotBlank(sellerInvoiceEntity.getInvoiceDate())){
            vo.setKprq(sellerInvoiceEntity.getInvoiceDate().replaceAll("-",""));
        }
        vo.setDw(sellerInvoiceDetailEntityList.get(0).getTonnage());
        vo.setTspz("00");
        vo.setJym(sellerInvoiceEntity.getCheckCode());
        vo.setXcrs(sellerInvoiceDetailEntityList.get(0).getMaximumPeople());
        vo.setYhzcbs("");
        vo.setSlbs("");
        vo.setZzstsgl("");
        vo.setBz(sellerInvoiceEntity.getRemark());
        vo.setKpr(sellerInvoiceEntity.getDrawer());
        vo.setYkprq("");
        return vo;
    }

    /**
     * 根据税号和发票类型获取打印机信息
     * @return
     */
    public Response getSellerPrintConfig(PrinterConfigVO vo){
        SellerPrintConfigEntity sellerInvoiceEntity = new SellerPrintConfigEntity();
        try {
            sellerInvoiceEntity = baseMapper.selectOne(new QueryWrapper<SellerPrintConfigEntity>().eq("seller_tax_no",vo.getSellerTaxNo()).eq("invoice_type",vo.getInvoiceType()));
        }catch (Exception e){
            log.info("-1", e);
            sellerInvoiceEntity = null;
        }
        return Response.success(sellerInvoiceEntity);
    }

    /**
     * 获取发票信息
     * @return
     */
    public Response getInvoiceService(PrintReqVO vo){
        if(StrUtil.isBlank(vo.getSerialNo())){
            return Response.error("SEL_107");
        }
        SellerInvoiceEntity sellerInvoiceEntity = invoiceService.getOne(new QueryWrapper<SellerInvoiceEntity>().eq("serial_no", vo.getSerialNo()));
        QueryWrapper<SellerInvoiceDetailEntity> invoiceEntityQueryWrapper = new QueryWrapper<>();
        invoiceEntityQueryWrapper.eq("serial_no", vo.getSerialNo());
        invoiceEntityQueryWrapper.orderByAsc("invoice_sort");
        List<SellerInvoiceDetailEntity> sellerInvoiceDetailEntityList = invoiceDetailService.list(invoiceEntityQueryWrapper);
        if(sellerInvoiceEntity == null || sellerInvoiceDetailEntityList == null || sellerInvoiceDetailEntityList.size() == 0){
            return Response.error("SEL_107");
        }
        String listFlag = vo.getListFlag();
//        int invoiceDetailNum = sellerInvoiceDetailEntityList.size();
//        if (invoiceDetailNum>=8) {
//            listFlag = CodeConstant.COMM_CODE_1;
//        } else {
//            listFlag = CodeConstant.COMM_CODE_0;
//        }
        try {
            //保存打印机配置信息
            SellerPrintConfigEntity sellerUserPrintEntity = (SellerPrintConfigEntity) getSellerPrintConfig(new PrinterConfigVO(sellerInvoiceEntity.getSellerTaxNo(),sellerInvoiceEntity.getInvoiceType())).getData();
            if (sellerUserPrintEntity == null) {
                sellerUserPrintEntity = new SellerPrintConfigEntity(
                        UUIDUitl.UUID32(false),
                        sellerInvoiceEntity.getSellerTaxNo(),
                        sellerInvoiceEntity.getInvoiceType(),
                        vo.getLeft(),
                        vo.getTop(),
                        vo.getPrintName());
                baseMapper.insert(sellerUserPrintEntity);
            } else {
                sellerUserPrintEntity.setInvoiceLeft(vo.getLeft());
                sellerUserPrintEntity.setInvoiceTop(vo.getTop());
                sellerUserPrintEntity.setPrintName(vo.getPrintName());
                baseMapper.updateById(sellerUserPrintEntity);
            }
        }catch (Exception e){
            log.error("保存打印机配置信息异常",e);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("fplxdm",  PrinterConstant.coverInvoiceType(sellerInvoiceEntity.getInvoiceType()));
        map.put("left", vo.getLeft());
        map.put("top", vo.getTop());
        map.put("sfyl", "1");
        map.put("qdbz", listFlag);
        map.put("printName", vo.getPrintName());
        map.put("fpxx",JSON.toJSONString(invoiceToPrinterVo(sellerInvoiceEntity,sellerInvoiceDetailEntityList), SerializerFeature.WriteNullStringAsEmpty));
        log.info("++++++++++++"+map.toString()+"++++++++++++++++++");
        return Response.success(map);
    }

    /**
     * 获取发票信息List
     * @return
     */
    public Response getInvoiceListService(PrintReqVO vo){
        if(vo.getSerialNoList() == null || vo.getSerialNoList().isEmpty()){
            return Response.error("SEL_107");
        }
        List<SellerInvoiceEntity> sellerInvoiceEntityList = invoiceService.list(new QueryWrapper<SellerInvoiceEntity>().in("serial_no", vo.getSerialNoList()));
        if(sellerInvoiceEntityList == null || sellerInvoiceEntityList.isEmpty()){
            return Response.error("SEL_113");
        }
        Map <String,List<SellerInvoiceEntity>> mapCollect = sellerInvoiceEntityList.stream().collect(Collectors.groupingBy(SellerInvoiceEntity::getSellerTaxNo));
        if(mapCollect.size() > 1 || mapCollect.size() == 0){
            return Response.error("SEL_114");
        }
        String listFlag = null;
        int invoiceDetailNum = sellerInvoiceEntityList.size();
        if (invoiceDetailNum>=8) {
            listFlag = CodeConstant.COMM_CODE_0;
        } else {
            listFlag = CodeConstant.COMM_CODE_1;
        }
        Map<String, Object> map = new HashMap<>();
        map.put("left", vo.getLeft());
        map.put("top", vo.getTop());
        map.put("sfyl", "1");
        map.put("qdbz", listFlag);
        map.put("printName", vo.getPrintName());
        map.put("fplxdm",  PrinterConstant.coverInvoiceType(sellerInvoiceEntityList.get(0).getInvoiceType()));
        for (SellerInvoiceEntity  sellerInvoiceEntity:sellerInvoiceEntityList){
            try {
                //保存打印机配置信息
                SellerPrintConfigEntity sellerUserPrintEntity = (SellerPrintConfigEntity) getSellerPrintConfig(new PrinterConfigVO(sellerInvoiceEntity.getSellerTaxNo(),sellerInvoiceEntity.getInvoiceType())).getData();
                if (sellerUserPrintEntity == null) {
                    sellerUserPrintEntity = new SellerPrintConfigEntity(
                            UUIDUitl.UUID32(false),
                            sellerInvoiceEntity.getSellerTaxNo(),
                            sellerInvoiceEntity.getInvoiceType(),
                            vo.getLeft(),
                            vo.getTop(),
                            vo.getPrintName());
                    baseMapper.insert(sellerUserPrintEntity);
                } else {
                    sellerUserPrintEntity.setInvoiceLeft(vo.getLeft());
                    sellerUserPrintEntity.setInvoiceTop(vo.getTop());
                    sellerUserPrintEntity.setPrintName(vo.getPrintName());
                    baseMapper.updateById(sellerUserPrintEntity);
                }
            }catch (Exception e){
                log.error("保存打印机配置信息异常",e);
            }

        }
        map.put("fpxx",JSON.toJSONString(invoiceListToPrinterVo(sellerInvoiceEntityList), SerializerFeature.WriteNullStringAsEmpty));
        return  Response.success(map);
    }

    /**
     * 发票信息转换List
     * @param sellerInvoiceEntity
     * @return
     */
    private PrinterServiceRespVO invoiceListToPrinterVo(List<SellerInvoiceEntity> sellerInvoiceEntity){
        PrinterServiceRespVO vo = new PrinterServiceRespVO();
        vo.setFplxdm(PrinterConstant.coverInvoiceType(sellerInvoiceEntity.get(0).getInvoiceType()));
        vo.setNsrmc(sellerInvoiceEntity.get(0).getSellerName());
        vo.setNsrsbh(sellerInvoiceEntity.get(0).getSellerTaxNo());
        vo.setSbbh("0");
        vo.setData(sellerInvoiceToPrinterVo(sellerInvoiceEntity,null,null));
        return vo;
    }

    /**
     * 获取税编名称用于发票打印
     * @param taxCode
     */
    private String getTaxName(String taxCode){
        String taxName = baseMapper.getTaxNameByTaxCode(taxCode);
       return "*"+taxName+"*";
    }

    /**
     * 发票预打印
     * @param synchronizeInvoiceDTO
     * @return
     */
    public Response getLocalYdy(SynchronizeInvoiceDTO synchronizeInvoiceDTO) {
        Response res = new Response();
        //获取开票设备
        String sellerTaxNo = synchronizeInvoiceDTO.getSellerTaxNo();
        EquipmentEntity equipmentEntity = equipmentService.getOne(new QueryWrapper<EquipmentEntity>().eq("seller_tax_no", sellerTaxNo).eq("disable", "1"));
        if (null == equipmentEntity) {
            res.setCode("T0001");
            res.setMsg("同步失败，该纳税人识别号对应的设备未添加或开启，请检查！");
            return res;
        }
        //设备类型
        String json = IntJsonUtil.localYdy(equipmentEntity,synchronizeInvoiceDTO);
        SellerInvoiceDTO sellerInvoiceDTO = new SellerInvoiceDTO();
        sellerInvoiceDTO.setBw(json);
        Response response = apiClientService.callSST(sellerInvoiceDTO);
        String result = (String) response.getData();
        JSONObject jsonObject = (JSONObject) JSON.parse(result);
        String code = jsonObject.getString("code");
        String msg = jsonObject.getString("msg");
        if (CodeConstant.THIRD_PARTY_SUCCESS.equals(code)) {
            List resList = (List) jsonObject.get("data");
            SyncInvoiceDTO syncInvoiceDTO = new SyncInvoiceDTO();
            syncInvoiceDTO.setEquipmentMode(equipmentEntity.getEquipmentMode());
            syncInvoiceDTO.setSellerName(synchronizeInvoiceDTO.getSellerName());
            syncInvoiceDTO.setSellerTaxNo(synchronizeInvoiceDTO.getSellerTaxNo());
            invoiceService.updateSellerInvoiceInfoSST(resList,syncInvoiceDTO);
        }else {
            return Response.error(CodeConstant.T0001,msg);
        }
        return Response.success();
    }
}
